import React, { Component } from 'react';
import './index.scss';

class Editor extends Component {
  constructor() {
    super();
    this.state = {
      showText: '',
      bold: false,
      italic: false,
      size: 3,
      fontSize: [
        '最小', '较小', '中等', '较大', '最大'
      ]
    };
  }
  componentDidMount() {
    this.timerID = setInterval(
      // () => this.tick(),
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }
  changeTextStyle (prop) {
    this.refs.myEditor.focus()
    document.execCommand(prop, false, null)
    if (prop === 'Bold') {
      let val = !this.state.bold
      this.setState({bold: val })
    }
    if (prop === 'Italic') {
      let val = !this.state.italic
      this.setState({italic: val })
    }
  }
  // // 改变文本字体，设置了四档字体大小
  // // execCommand方法只支持到1-7的font-size
  // // 后续尝试优化这块儿
  changeFontSize () {
    console.log(this.state.size)
    if (this.state.size === 7) {
      this.setState({size: 3 })
    }
    else {
      let val = this.state.size
      this.setState({size: val + 1 })
    }
    this.refs.myEditor.focus()
    // document.getElementById('text-area').focus()
    document.execCommand('FontSize', false, this.state.size)
  }
  // 清空编辑内容
  clearText () {
    const el = document.getElementById('text-area')
    el.innerHTML = ''
    el.focus()
  }
  submitText() {
    const el = document.getElementById('text-area');
    console.log(el.innerHTML)
    this.setState({showText: el.innerHTML});
    console.log(this.state.showText)
  }

  render() {
    return (
      <div className="container">
        <h1>一个简易的富文本编辑组件</h1>
        <div className="edit">
          <div className="edit-control">
            <button title="加粗" onClick={()=>this.changeTextStyle("Bold")}>B</button>
            <button title="斜体" onClick={()=>this.changeTextStyle("Italic")}>I</button>
            <button title="改变字体大小" onClick={()=>this.changeFontSize()}>H</button>
            <button title="清空文本" onClick={this.clearText}>清除</button>
          </div>
          <div id="text-area" ref="myEditor" contentEditable="true"></div>
          <button className="edit-submit" onClick={()=>this.submitText()}>提交文本</button>
        </div>
        <h2>编辑结果</h2>
        <div className="show">
          <div dangerouslySetInnerHTML={{__html: this.state.showText}}></div>
        </div>
      </div>
    );
  }

}

export default Editor;
